<?php
Namespace Cyfy\Modules\Administration;

/**
 * General administration module.
 *
 * General administration module, allows to show main page with all modules, which have administration method.
 * Another feature is called FastNavigation. That allows everybody to set, whatever they want to display in navigation.
 *
 * @version 0.1
 * @author Dandelion <dandelion8888@gmail.com>
 */
class Module extends \Cyfy\Module
{
    /**
     * Show module name in Fast Navigation
     * @var bool
     */
    static public $fastNavigationShowModule = true;
    
    /**
     * Method handling AJAX calls.
     *
     * Available methods are:
     * <ul>
     *    <li>saveBlock - saves the Fast Navigation block for current user</li>
     * </ul>
     * If no method found, returns FALSE.
     *
     * @param string Called method name.
     * @return mixed AJAX callback result or FALSE.
     */
	static public function ajax($name)
	{
		switch($name)
		{
			case 'saveBlock':
				return self :: ajaxSaveNavigation();
		}
        return false;
	}
        
    /**
     * Returns list of blocks or HTML content of called block.
     *
     * <ul>
     *     <li>If $name is an empty string, returns a list of available blocks.</li>
     *     <li>If $name is not empty, then it returns content of called block. If the block doesn't exist, returns FALSE.</li>
     * </ul>
     * @param string Name of the block
     * @return mixed Associative array of blocks, HTML content - string, or FALSE.
     */
	static public function blocks($name = '')
	{
		switch($name)
        {
            // fast navigation
            case 'fastNavigation':
                return self :: fastNavigation();
            
            // list of blocks
            case '':
                return array('fastNavigation' => self :: t(200));
            
            // unknown
            default:
                return false;
		}
	}
    
    /**
     * Returns main administration page - list of available commands or an administration inteface, if something selected.
     * @return string HTML content
     */
	static function get($name)
	{
		// Permission check
		if(!\Cyfy\Cyfy ::  permission('Administration', 'see administration'))
        {
            return \Cyfy\Cyfy ::  noPermission(true);
        }
        
        // If something selected
		if(\Cyfy\Cyfy ::  $query != 'administration')
		{
            // administration selected
            if(\Cyfy\Cyfy ::  arg(2))
            {
                return self :: showInterface();
            }
            
            // only module selected
            return self :: showModuleDetails(\Cyfy\Cyfy ::  arg(1));
		}

        // else return main
        return self :: main();
    }
    
    
    
    static function showModuleDetails($module)
    {
        // LOAD NAMES FIRST
        $class = '\Cyfy\Modules\\' . $module . "\Module";

        // class exists
        if(!file_exists(classToPath($class) . '.php')) return false;

        // if administration exists
        if(!method_exists($class, "administration")) return false;
        
        // get method with list of options
        $functions = $class :: administration();
        if(!is_array($functions)) return false;
        
        $name = $module;
        $name = $class :: getName();
        
        $data = "";
        foreach($functions as $path => $parameters)
        {
            // if permission necessary
            if($parameters["permission"])
            {
                // check user for permission
                if(!\Cyfy\Cyfy ::  permission($module, $parameters["permission"]))
                {
                    continue;
                }
            }
            
            // ADD DATA
            $data .= "<h3><a href=\"" . \Cyfy\Cyfy ::  getPath("administration/" . $module . "/" . $path) . "\">" . $parameters["name"] . "</a></h3>\n<p class=\"administration-description\">" . $parameters["description"] ."</p>\n";
        }
        if($data == ""){
            return false;
        }
        
// content
$output = <<<OUTPUT
<h2>{$name}</h2>	
{$data}						
OUTPUT;
// end content
        
        return $output;
    
    }
    
    
    /**
     * List of all modules with administration options
     * @return string HTML content
     */
    static private function main()
    {
        \Cyfy\Cyfy ::  CSS(\Cyfy\Cyfy ::  getSourcePath('Cyfy/Modules/Administration/style.css'), 'file');
        \Cyfy\Cyfy ::  JavaScript(\Cyfy\Cyfy ::  getSourcePath('Cyfy/Modules/Administration/scripts.js'), 'file');
		
        // Message to be shown for Fast Navigation
		$msg = self :: t(210);
      
        // Current selection of fast administration
        $active = array();
        $result = \dibi :: query("SELECT [module], [name] FROM [:cyfy:Administration-block] WHERE uid = %i", \Cyfy\Modules\Users\Current :: $uid, " AND [language] = %s", \Cyfy\Language :: getActive());
        foreach($result as $r)
        {
            $active[$r["module"]][$r["name"]] = true;
        }
        
        // title and header
        \Cyfy\Template :: setTitle(self :: t(10));
        $output = "<h2>" . self :: t(10) . "</h2>";
        $output .= "<p>" . self :: t(20) . "</p>";
        $output .= "<p>" . self :: t(30) . "</p>";

        // LOAD NAMES FIRST
        $names = array();
        foreach(\Cyfy\Modules :: getEnabled() as $module)
        {
            $class = '\Cyfy\Modules\\' . $module . "\Module";
            // class exists
            if(!file_exists(classToPath($class) . '.php')) continue;
            // if administration exists
            if(!method_exists($class, "administration")) continue;
            // get method with list of options
            $functions = $class :: administration();
            if(!is_array($functions)) continue;
            
            $name = $module;
            $name = $class :: getName();
            
            $names[$module] = $name;
        }
        
        // SORT array
        asort($names);
        
        // Module counter
		$i = 0;

        foreach($names as $module => $name)
        {
            // Going through modules
            $i++;

            // classname
            $class = '\Cyfy\Modules\\' . $module . "\Module";
            
            // get method with list of options
            $functions = $class :: administration();
            if(!is_array($functions)) continue;
            
            
            $data = "";
            foreach($functions as $path => $parameters)
            {
                // if hidden
                if($parameters["hidden"]) continue;
                
                // if permission necessary
                if($parameters["permission"])
                {
                    // check user for permission
                    if(!\Cyfy\Cyfy ::  permission($module, $parameters["permission"]))
                    {
                        continue;
                    }
                }
                // OK
                $i++;
                
                // CHECKED?
                if($active[$module][$path]){
                    $checked = "checked=\"checked\"";
                }else{
                    $checked = "";
                }
                
                // ADD DATA
                $data .= "<div class=\"moduleAdmininstration\"><div class=\"showInMenu\"><input type=\"hidden\" class=\"showModuleTitle-{$i}\" value=\"" . $parameters["name"] ."\" /><input type=\"hidden\" class=\"showModuleName-{$i}\" value=\"" . $path . "\" /><input type=\"hidden\" class=\"showModuleModule-{$i}\" value=\"" . $module . "\" /><input type=\"checkbox\" name=\"\" {$checked} value=\"".$i."\" class=\"showModule\" /> {$msg}</div><h3><a href=\"" . \Cyfy\Cyfy ::  getPath("administration/" . $module . "/" . $path) . "\">" . $parameters["name"] . "</a></h3></div>\n";
            }
            if($data != "")
            {
                
// content
$output .= <<<OUTPUT
<h2 class="moduleAdmininstrationHeader">{$name}</h2>	
{$data}						
OUTPUT;
// end content
            }
        }
        return $output;
    }
    
    /**
     * Returns an interface when is called.
     * @return string HTML content
     */
    static private function showInterface()
    {
        $class = '\Cyfy\Modules\\' . \Cyfy\Cyfy ::  arg(1) . "\Module";
        $administration = \Cyfy\Cyfy ::  arg(2);
        
        // Does the administration exist?
        if(method_exists($class, "administration"))
        {
            // Information about all methods
            $all = $class :: administration();
            
            // Permission
            $permission = $all[$administration]["permission"];
            if($permission)
            {
                // Checks user for permission.
                if(!\Cyfy\Cyfy ::  permission(\Cyfy\Cyfy ::  arg(1), $permission))
                {
                    // no permission
                    return \Cyfy\Cyfy ::  noPermission(true);
                }				
            }	
            // title
            \Cyfy\Template :: setTitle($all[$administration]["name"]);
            
            // ok, continue
            $data = $class :: administration($administration);
            
            if($data)
            {
                return "<h2>" . $all[$administration]["name"] . "</h2><p>" . $all[$administration]["description"] . "</p>\n" . $data;
            }
        }
    }

    /**
     * Saves Fast Administration navigation.
     */
    static private function ajaxSaveNavigation()
	{
        \dibi :: query("DELETE FROM [:cyfy:Administration-block] WHERE uid = %i", \Cyfy\Modules\Users\Current :: $uid, " AND [language] = %s", \Cyfy\Language :: getActive());
		if(is_array($_POST["name"]) && is_array($_POST["title"]) && is_array($_POST["moduleName"]))
		{
			for($i=0; $i<count($_POST["name"]); $i++)
			{
                $values = array(
                    'uid' => \Cyfy\Modules\Users\Current :: $uid,
                    'language' => \Cyfy\Language :: getActive(),
                    'module' => $_POST["moduleName"][$i],
                    'name' => $_POST["name"][$i],
                    'title' => $_POST["title"][$i]
                );
				\dibi :: query("INSERT INTO [:cyfy:Administration-block]", $values);
			}
			\Cyfy\Message :: set(self :: t(220));
		}
        else
        {
			\Cyfy\Message :: set(self :: t(230), \Cyfy\Message :: WARNING);
		}
	}
    
    /**
     * Returns Fast Navigation for currently logged user
     */
	static private function fastNavigation()
	{
		// Checks user for permission.
		if(!\Cyfy\Cyfy ::  permission("Administration", "see administration"))
        {
            return "";
        }		
        
        // DB query
		$result = \dibi :: query("SELECT [module], [name], [title] FROM [:cyfy:Administration-block] WHERE [uid] = %i", \Cyfy\Modules\Users\Current :: $uid, " AND [language] = %s", \Cyfy\Language :: getActive(), " ORDER BY [module], [title] ASC");
        $output .= "<h3><span><a href=\"" . \Cyfy\Cyfy ::  getPath("administration") . "\">" .  self :: t(10) . "</a></span></h3>\n	<ul class=\"menu\">";

        // items
        $previousModule = "";
        foreach($result as $n)
        {
            // display module name?
            if(self :: $fastNavigationShowModule && $previousModule != $n["module"])
            {
                // name
                $class = '\Cyfy\Modules\\' . $n["module"] . "\Module";
                $output .= "		<li><h4>" . $class :: getName() . "</h4></li>\n";
            }			
            // display link
            $output .= "		<li><a href=\"" . \Cyfy\Cyfy ::  getPath("administration/" . $n["module"] . "/" . $n["name"]) . "\">" . $n["title"] ."</a></li>\n";
        
            // memory
            $previousModule=$n["module"];
        }
        $output .= "	</ul>\n";
        return $output;
	}
}